package com.medical_houduan.filter;

import com.medical_houduan.utils.JwtUtil;
import com.medical_houduan.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;


//拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证(通过HttpServletRequest对象获取令牌)
        String token = request.getHeader("Authorization");
        //验证token（在请求头获取）
        try {
            //解析出来的token（包含用户数据）
            Map<String, Object> claims = JwtUtil.parseToken(token);//如果token有问题会报异常
            //把用户数据存入ThreadLocal（详见utils包下），实现共享
            ThreadLocalUtil.set(claims);
            System.out.println(claims+"1111.......");

            return true;//token没问题，放行
        } catch (Exception e) {
            response.setStatus(401);//通过HttpServletResponse类设置http响应状态码为401
            System.out.println("222222...........");
            return false;//token有问题
        }


    }


    //当这一次请求完成后，最后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //清空ThreadLocal中的数据，防止内存泄漏
        ThreadLocalUtil.remove();

        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
